<template>
  <table>
    <thead>
      <tr>
        <th v-for="key in colunms" :key="key" @click="sortBy(key)" :class="{active:sortKey===key}">
          {{key|capitalize}}<span class="arrow" :class="sortOrders[key]>0?'asc':'dsc'"></span>
        </th>
      </tr>
          </thead>
      <tbody>
        <tr v-for="entry in filterData" >
          <td v-for="key in colunms" >
            {{entry[key]}}
          </td>
        </tr>
      </tbody>

  </table>
</template>
<script>
  export default {
    props: {
      colunms: Array,
      data: Array,
      queryKey: String
    },
    data() {
      const sortOrders = {}
      this.colunms.forEach(item => {
        sortOrders[item] = 1
      })
      return {
        sortKey: '',
        sortOrders: sortOrders
      }
    },
    computed: {
      filterData() {
        const sortKey = this.sortKey
        const queryKey = this.queryKey && this.queryKey.toLowerCase()
        const order = this.sortOrders[sortKey] || 1
        let data = this.data
        if (queryKey) {
          data = data.filter(row => {
            return Object.keys(row).some(key => {
              return String(row[key]).toLowerCase().indexOf(queryKey) > -1
            })
          })
        }
        if (sortKey) {
          data = data.slice().sort((a, b) => {
            a = a[sortKey]
            b = b[sortKey]
            return (a === b ? 0 : a > b ? 1 : -1) * order
          })
        }
        return data
      }
    },
    filters: {
      capitalize(key) {
        return key.charAt(0).toUpperCase() + key.slice(1)
      }
    },
    methods: {
      sortBy(key) {
        this.sortKey = key
        this.sortOrders[key] *= -1
      }
    }
  }

</script>
<style lang="scss" scoped>

table {
  border: 2px solid #42b983;
  border-radius: 3px;
  backgr-radius: 3px;
  color: #444;
}
th {
  background-color: #42b983;
  color: rgba(255,255,255,0.66);
  cursor: pointer;
  user-select: none;
}

td {
  background-color: #f9f9f9;
}

th, td {
  min-width: 120px;
  padding: 10px 20px;
}
th.active{
  color:#fff;
  .arrow{
    opacity: 1;
  }
}
.arrow{
  display: inline-block;
  vertical-align: middle;
  width: 0;
  height: 0;
  margin-left: 5px;
  opacity: 0.66;
}
.arrow.asc{
  border-left: 4px solid transparent;
  border-right: 4px solid transparent;
  border-bottom: 4px solid #fff;
}

.arrow.dsc {
  border-left: 4px solid transparent;
  border-right: 4px solid transparent;
  border-top: 4px solid #fff;
}
</style>

